<?php
/**
 * 跃飞科技版权所有 @2017
 * User: 钟贵廷
 * Date: 2017/5/17
 * Time: 10:12
 */
namespace app\admin\controller;
use app\admin\model\Config;
use think\Controller;

class Admin extends Controller
{
    private $appId;
    private $appSecret;
    private $last_time;

    public function __construct()
    {
        parent::__construct();
        if(!session('?userId'))
        {
            $this->error('请登录！',url('admin/manager/login'));
        }
    }


    //获取access_token（支持自动更新凭证）
    public function get_access_token()
    {
        $config = new Config();
        $this->last_time =  $config->where('key','access_token')->value('add_time');
        $access_token =  $config->where('key','access_token')->value('value');
        $this->appId =  $config->where('key','appId')->value('value');
        $this->appSecret =  $config->where('key','appSecret')->value('value');
        if(time() > ($this->last_time + 7200))
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";
            $access_token_Arr =  $this->https_request($url);
            $this->last_time = time();
            $access_token =  $access_token_Arr['access_token'];
            //更新数据库
            $config->where(['key'=>'access_token'])->update(['value'=>$access_token,'add_time'=>$this->last_time]);
        }
        return $access_token;
    }

    //https请求（支持GET和POST）
    protected function https_request($url,$data = null)
    {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        if(!empty($data))
        {
            curl_setopt ($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch,CURLOPT_POST,1);//模拟POST
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//POST内容
        }
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    /**
     * 不转义中文跟斜杠
     * @param $input
     * @return mixed
     */
    public function cn_json_encode($input)
    {
        $input = json_encode($input, JSON_UNESCAPED_UNICODE);
        return str_replace("\\/", "/",  $input);
    }

    public function test()
    {
        $config = new Config();
        p($config::all()->toArray());
        $a =  $config->where('key','appId')->value('value');
        p($a);
    }

}
